var express = require('express');
var router = express.Router();
var user_m = require('../models/users');

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.render('index', {title: 'user'});
});

router.get('/reg', function(req, res, next) {
    res.render('reg', {errmsg: ''}); // 加载模板
});

router.post('/reg', function(req, res, next) {
    var request = req.body;
    var username = request.username || '';
    var password = request.password || '';
    var password2 = request.password2 || '';
    
    if(password !== password2) {
        res.render('reg', {errmsg: '密码不一致'});
        return ;
    }

    var password_hash = user_m.hash(password);
    var regtime = parseInt(Date.now() / 1000);

    user_m.reg(username, password, regtime, function(res) {
        if(res.isExisted) {
            res.render('reg', {errmsg: '用户名已存在'});
        } else if(res.affectedRows) {
            res.redirect('/');
        } else {
            res.render('reg', {errmsg: '注册失败'});
        }
    });

});

module.exports = router;
